<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
  <title>deferred test</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <script type="text/javascript" src="deferred.js"></script>
</head>
<body>
  <script type="text/javascript">
if(
  typeof HTMLElement!='undefined'&&
  typeof HTMLElement.prototype.insertAdjacentHTML=='undefined'
){
  HTMLElement.prototype.insertAdjacentHTML=function (sWhere,sHTML) {
    var t=this,
    r=t.ownerDocument.createRange(),
    a={
      'beforebegin':['setStartBefore',t.parentNode,t],
      'afterbegin':['selectNodeContents',t,t.firstChild,!0],
      'beforeend':['selectNodeContents',t,null,!1],
      'afterend':['setStartAfter',t.parentNode,t.nextSibling]
    }[sWhere.toLowerCase()];
    r[a[0]](t);
    a.length==4 && r.collapse(a[3]);
    a[1].insertBefore(r.createContextualFragment(sHTML),a[2])
  }
}
/* ---------------------- */
var drawTest = (function(){
  var prevTime =0;
  return function drawTest(value){
    var
    t = (new Date()).getTime(),
    a = [
      '<div>',
      value,
      '<div style="font-size:10px;text-align:right;background:#ccc">',
      t - prevTime,
      'ms</div></div>'
    ];
    prevTime = t;
    document.body.insertAdjacentHTML('beforeend',a.join(''))
  }
})();
drawTest('начало');
//debugger;
var done=0, timer, testDeferred = new djp.deferred();
testDeferred.addWatchers(
  function onResultCallback1(res){
    drawTest('Callback1: '+res);
    return ['изменил результат '+done+' раз',0]
  },
  function onErrorCallback(err){
    drawTest(err)
  },
  function onCancelCallback(){
    drawTest('cancel '+done+' раз')
  }
).addWatchers(
  function onResultCallback2(res){
    var subDeferred = new djp.deferred();
    drawTest('Callback2: '+res);
    setTimeout(function(){
//      debugger;
      drawTest('setDeferredValue: '+'subDeferred '+done+' раз');
      subDeferred.setValue('subDeferred '+done+' раз')
    },100);
    return subDeferred
  }
);
timer = setInterval(function(){
  drawTest('setValue: '+'0.1секунда прошла '+done+' раз');
  testDeferred.setValue('0.1секунда прошла '+done+' раз');
  if (!done) {
    testDeferred.addWatchers(
      function onResultCallback3(res){
        drawTest('Callback3: '+res)
      },
      0,
      function onCancelCallback3(){
        drawTest('cancel3 '+done+' раз')
      }
    );
  };
  if ((++done)>=3) clearInterval(timer);
},1000);
/*
setTimeout(function(){
  testDeferred.cancel()
},910);
*/
  </script>
</body>
</html>